<template>
    <el-card shadow="always" :body-style="{ padding: '20px' }">
        <template #header>
            <el-row :gutter="20">
                <el-col :span="12">仓库管理</el-col>
                <el-col :span="12" class="text-right">
                    <el-button type="primary" @click="showAddDrawer">添加仓库</el-button>
                </el-col>
            </el-row>
        </template>

        <!-- 搜索栏 -->
        <!-- <div>
            <el-form :inline="true" :model="searchForm" class="responsive-form">
                <el-form-item label="仓库位置">
                    <el-input v-model="searchForm.location" placeholder="请输入仓库位置" @keyup.enter="handleSearch"
                        style="min-width: 200px;"></el-input>
                </el-form-item>
                <el-form-item label="仓库名称">
                    <el-input v-model="searchForm.name" placeholder="请输入仓库名称" @keyup.enter="handleSearch"
                        style="min-width: 200px;"></el-input>
                </el-form-item>

                <el-form-item class="form-buttons">
                    <el-button type="primary" @click="handleSearch">搜索</el-button>
                    <el-button @click="handleReset">重置</el-button>
                </el-form-item>
            </el-form> -->

            <el-table :data="warehouses" v-loading="loading" style="width: 100%">
                <el-table-column fixed label="ID" prop="id" width="80"></el-table-column>
                <el-table-column label="名称" prop="name" min-width="120"></el-table-column>
                <el-table-column label="位置" prop="location" min-width="120"></el-table-column>
                <el-table-column label="创建人" prop="created_by" width="100"></el-table-column>
                <el-table-column fixed="right" label="操作" width="180">
                    <template #default="{ row }">
                        <el-button type="primary" size="small" @click="handleEdit(row)">修改</el-button>
                        <el-button type="danger" size="small" @click="handleDelete(row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>

            <!-- 分页 -->
            <!-- <el-pagination @current-change="handlePageChange" :current-page="currentPage" :page-size="PAGE_SIZE"
                :total="totalPets" layout="total, prev, pager, next" class="mt-4"></el-pagination>
        </div> -->

        <!-- 宠物添加/编辑抽屉 -->
        <el-drawer v-model="drawerVisible" :title="drawerTitle" size="50%" direction="rtl" :destroy-on-close="true">
            <AddAnimalSet v-if="dialogType === 'add'" @cancel="handleCancel" @success="handleSuccess" />
            <EditAnimalSet 
                v-if="dialogType === 'edit' && drawerVisible" 
                :key="currentWarehouse?.id" 
                :warehouseData="currentWarehouse" 
                @cancel="handleCancel"
                @success="handleSuccess" 
            />
        </el-drawer>
    </el-card>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import AddAnimalSet from './addAnimalSet.vue';
import EditAnimalSet from './editAnimalSet.vue';
import { getWarehouses, addWarehouse, updateWarehouse, deleteWarehouse } from '@/api/warehouse';


// 常量
const PAGE_SIZE = 20;

// 数据定义
const warehouses = ref([]); 
const loading = ref(false);
const drawerVisible = ref(false);
const dialogType = ref('add');
const currentWarehouse = ref(null);
const currentPage = ref(1);
// const totalWarehouses = ref(0);

const searchForm = ref({
    location: '',
    name: ''
});

// 计算属性
const drawerTitle = computed(() => {
    return dialogType.value === 'add' ? '添加仓库' : '编辑仓库';
});

// 方法定义
const fetchWarehouses = async () => {
    loading.value = true;
    try {
        const res = await getWarehouses();
        // 修改解构变量名，避免冲突
        const {code, message } = res.data; 
        if (code === 200) {
            warehouses.value = res.data.warehouses;
            // console.log(warehouses.value);
        } else {
            ElMessage.error(message);
        }
    } catch (error) {
        ElMessage.error('获取仓库列表失败：' + error.message);
    } finally {
        loading.value = false;
    }
};

// const handleSearch = () => {
//     currentPage.value = 1;
//     fetchWarehouses();
// };

// const handleReset = () => {
//     searchForm.value.location = '';
//     searchForm.value.name = '';
//     handleSearch();
//     fetchWarehouses(); // 刷新仓库列表
// };

// const handlePageChange = (page) => {
//     currentPage.value = page;
//     fetchWarehouses();
// };

const showAddDrawer = () => {
    dialogType.value = 'add';
    drawerVisible.value = true;
};

const handleEdit = (row) => {
    dialogType.value = 'edit';
    // 创建一个新的对象来避免引用问题
    currentWarehouse.value = JSON.parse(JSON.stringify(row));
    console.log("currentWarehouse",JSON.parse(JSON.stringify(row)));
    
    drawerVisible.value = true;
};

const handleDelete = (row) => {
    ElMessageBox.confirm('确定要删除这个仓库吗？', '提示', {
        type: 'warning'
    }).then(async () => {
        try {
            const { data } = await deleteWarehouse({ id: row.id });
            if (data.code === 200) {
                ElMessage.success('删除成功');
                fetchWarehouses();
            } else {
                ElMessage.error(data.message || '删除失败');
            }
        } catch (error) {
            ElMessage.error('删除失败：' + error.message);
        }
    }).catch(() => { });
};

const handleSuccess = () => {
    drawerVisible.value = false;
    fetchWarehouses(); // 刷新仓库列表
};

const handleCancel = () => {
    drawerVisible.value = false;
    currentWarehouse.value = null;
};

// 生命周期钩子
onMounted(() => {
    fetchWarehouses();
});
</script>

<style scoped>
.text-right {
    text-align: right;
}

.mt-4 {
    margin-top: 1rem;
}

.truncate-text {
    display: -webkit-box;
    -webkit-box-orient: vertical;
    overflow: hidden;
    text-overflow: ellipsis;
    line-height: 1.5;
    max-height: 3em;
    will-change: transform;
}

/* 添加表格滚动优化 */
:deep(.el-table__body-wrapper) {
    overflow-y: auto;
    scrollbar-width: thin;
}

:deep(.el-table) {
    transform: translateZ(0);
}

.responsive-form {
    display: flex;
    flex-wrap: wrap;
}

.form-buttons {
    margin-left: 0 !important;
    margin-top: 10px;
}

@media (max-width: 768px) {
    .el-form-item {
        margin-right: 0 !important;
        width: 100%;
    }
    
    .el-select {
        width: 100%;
    }
    
    .el-button {
        width: 100%;
        margin-bottom: 10px;
    }
}
</style>